package com.news.servlet;

import com.news.db.OpDB;
import com.news.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 实现登录
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");

        //2.获取数据
        //2.1获取用户填写验证码
        String verifycode = request.getParameter("verifycode");

        //3.验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            //提示信息
            request.setAttribute("login_msg","验证码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
            return;
        }

        //验证码正确，进行查询数据库
        OpDB opdb = new OpDB();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(username,password);
        String islogin = (String)request.getSession().getAttribute("islogin");
        if(islogin == null){
            if (opdb.OpLogin(user)){
                session.setAttribute("user",user);
                request.getSession().setAttribute("islogin","ok");
                //跳转页面
                response.sendRedirect("http://localhost:8080/news_war_exploded/admin/IndexTemp.jsp");
            }else{
                //登录失败
                //提示信息
                request.setAttribute("login_msg","用户名或密码错误！");
                //跳转登录页面
                request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("login_msg","你的session已存在，请不要重复登录！");
            //跳转登录页面
            request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

}
